<template>
  <div>
    <ListTab v-model="activeId" :tabs="tabList" :show-header="!showMobilePage" :mode="dimension" :mode-list="modeList" is-table @tabClick="handleTabClick" />
    <div class="supplier-account">
      <div :class="{'mobile-table mobile-min-height':showMobilePage}" class="table-list min-fill-page">
        <dataDisplay
          ref="dataDisplayRef"
          :data-list="[
            {data: statisticsData.settlementAmount / 100, label: '结算总金额', icon: incomeAmountIcon },
            {data: statisticsData.actualAmount / 100, label: '实付金额', icon: costIcon },
            {data: statisticsData.payedAmount / 100, label: '已支付金额', icon: rmb },
            {data: statisticsData.toPayAmount / 100, label: '待支付金额', icon: icon_7 }
          ]"
          style="margin-bottom:16px;"
        />
        <div v-if="!showMobilePage" class="supplier-tool">
          <div>
            <FilterInput
              ref="FilterToolRef"
              v-model="queryForm"
              :filter-list="filterList"
              show-search-btn
              is-show-config
              @handelClick="queryClick"
              @queryEmpty="queryEmpty"
              @filterTagStatus="filterTagStatus"/>
          </div>
          <div style="display:flex;align-items:center;height: 32px;margin-left: 26px;flex: 1;">
            <el-checkbox v-model="isShowMe" style="margin-right: 20px;" @change="queryClick" >我发起的</el-checkbox>
            <el-checkbox v-if="activeId !== -2" v-model="isMyApproval" style="margin-right: 20px;" @change="queryClick" >我审批的</el-checkbox>
            <el-checkbox v-model="isMyPending" @change="queryClick" >待我处理</el-checkbox>
          </div>
          <div class="opeator-bar">
            <div v-if="hasRouteAuth('crm:smartSettle:read')">
              <PlainCreateBtn
                :show-icon="false"
                type="primary"
                style="margin-right: 10px; padding: 8px 15px;"
                @click="goBatchSettle()">智能结算</PlainCreateBtn>
            </div>
            <div>
              <el-dropdown
                v-if="hasRouteAuth('medium:supplierAudit:launch')"
                trigger="click">
                <createBtn style="margin-right: 10px;" />
                <el-dropdown-menu slot="dropdown" style="padding:0;">
                  <el-dropdown-item style="width:130px;padding:0;text-align:center;" @click.native="toCreate(0)">
                    <div>订单成本付款结算</div>
                  </el-dropdown-item>
                  <el-dropdown-item style="width:130px;padding:0;text-align:center;" @click.native="toCreate(1)">
                    <div>其他付款结算(非订单)</div>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </div>
          <MoreOpeator
            ref="moreOpeatorRef"
            :list="MoreOpeatorList"
          />
        </div>
        <div v-loading="listLoading" style="min-height: 300px">
          <u-table
            v-if="list.items.length > 0"
            ref="tableRef"
            :data="list.items"
            :height="setTableHeight"
            :row-height="rowHeight()"
            :border="true"
            :row-class-name="tableRowClassName"
            beautify-table
            header-drag-style
            use-virtual
            class="fb-table"
            element-loading-text="加载中..."
            empty-text="暂无数据"
            header-cell-class-name="order-data-header-cell "
            fit
            hightlight-current-row
            @select="selectTable"
            @select-all="selectTable"
            @sort-change="sortMethod">
            <u-table-column
              :fixed="selectFixed"
              align="center"
              type="selection"
              width="50"/>
            <template v-if="!dimension">
              <u-table-column :min-width="handleTdWidth(100,185)" align="left" label="结算单号" label-class-name="diy-cell" class-name="diy-cell">
                <template slot-scope="scope" slot="header">
                  <div class="diyHeader">{{ scope.column.label }}</div>
                </template>
                <template slot-scope="scope">
                  <processSn :is-expedited="scope.row.isExpedited">
                    <span style="cursor:pointer;color:#406EFF" @click="toCheck(scope.row)">{{ scope.row.supplierNum ? handleSnNumber(scope.row.supplierNum) : '--' }}</span>
                  </processSn>
                </template>
              </u-table-column>
              <u-table-column :min-width="handleTdWidth(150,240)" align="left" label="结算名称">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.settleName" is-can-click @handelClick="toCheck(scope.row)" />
                </template>
              </u-table-column>
              <u-table-column :min-width="140" align="right" label="结算总金额(元)" sortable="custom" prop="settlementAmount">
                <template slot-scope="scope">
                  <PriceColumn :real-val="scope.row.settlementAmount" :price="scope.row.settlementAmount / 100" />
                </template>
              </u-table-column>
              <u-table-column :min-width="handleTdWidth(110,130)" align="right" label="实付金额(元)">
                <template slot-scope="scope">
                  <PriceColumn :real-val="scope.row.actualAmount" :price="scope.row.actualAmount / 100" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="成本来源" width="120">
                <template slot-scope="scope">
                  <ToolTip v-if="!scope.row.isNotOrder" :content="`${supplierCostBelong(scope.row.costBelong)}${scope.row.isInvite ? '(协作)' : ''}`" />
                  <div v-else>非订单</div>
                </template>
              </u-table-column>
              <u-table-column align="left" label="成本项" width="120">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.costItemName" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="发起方式" width="120">
                <template slot-scope="scope">
                  <div>{{ scope.row.createMethod?'智能结算':'手动新建' }}</div>
                </template>
              </u-table-column>
              <u-table-column align="left" label="当前节点" width="120">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.reviewRole" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="当前处理人" width="120">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.currentRole" />
                </template>
              </u-table-column>
              <u-table-column :min-width="handleTdWidth(100,120)" align="left" label="审批进度">
                <template slot-scope="scope">
                  <el-progress
                    v-if="handelProgess(scope.row.reviewProgress) || handelProgess(scope.row.reviewProgress) === 0"
                    :percentage="handelProgess(scope.row.reviewProgress)"
                    :stroke-width="10"
                    :format="() => scope.row.reviewProgress"
                    :color="`${handelProgess(scope.row.reviewProgress) === 100 ? '#31CC9C' : '#406eff'}`"
                    class="progress-cell" />
                  <el-tooltip v-else-if="scope.row.reviewProgress" :open-delay="800" placement="top-start" effect="dark">
                    <div slot="content" style="max-width:200px;"> {{ scope.row.reviewProgress }}</div>
                    <div class="ellipsis">{{ scope.row.reviewProgress }}</div>
                  </el-tooltip>
                  <div v-else>--</div>
                </template>
              </u-table-column>
              <u-table-column align="left" label="关联订单">
                <template slot-scope="scope">
                  <span>{{ scope.row.linkOrder || '--' }}</span>
                </template>
              </u-table-column>
              <u-table-column align="left" label="供应商" width="120">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.supplier" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="所属公司" width="120">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.company" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="状态" min-width="100">
                <template slot-scope="scope">
                  <div style="display:flex;align-items:center">
                    <div :style="scope.row.listStatus === 4?{backgroundColor: '#31CC9C'}:{backgroundColor: '#FD8546'}" class="dot"/>
                    <span>{{ getListStatus(scope.row.listStatus) }}</span>
                  </div>
                </template>
              </u-table-column>
              <u-table-column align="left" label="申请人">
                <template slot-scope="scope">
                  <CheckUserInfo v-if="scope.row.proposer" :label="scope.row.proposer" :user-id="scope.row.proposerId" />
                  <div v-else>--</div>
                </template>
              </u-table-column>
              <u-table-column align="left" label="申请人部门" width="140">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.proposerDepartmentName" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="账户类型" width="120">
                <template slot-scope="scope">
                  {{ scope.row.accountType | accountTypeStatus }}
                </template>
              </u-table-column>
              <u-table-column align="left" label="创建人">
                <template slot-scope="scope">
                  <CheckUserInfo v-if="scope.row.createUser" :label="scope.row.createUser" :user-id="scope.row.creatorId" />
                  <div v-else>--</div>
                </template>
              </u-table-column>
              <u-table-column align="left" label="创建时间" min-width="180" prop="createTime" sortable="custom">
                <template slot-scope="scope">
                  <span>{{ scope.row.createTime | format('YYYY/MM/DD HH:mm:ss') }}</span>
                </template>
              </u-table-column>
              <u-table-column align="left" label="计划支付日期" width="130" sortable="custom" prop="planPayTime">
                <template slot-scope="scope">
                  <span>{{ scope.row.planPayTime | format('YYYY/MM/DD') }}</span>
                </template>
              </u-table-column>
              <u-table-column align="left" label="实际支付日期" width="130" sortable="custom" prop="actualPayTime">
                <template slot-scope="scope">
                  <span>{{ scope.row.actualPayTime | format('YYYY/MM/DD') }}</span>
                </template>
              </u-table-column>
            </template>
            <template v-else>
              <u-table-column :min-width="handleTdWidth(100,185)" align="left" label="审批单号" label-class-name="diy-cell" class-name="diy-cell">
                <template slot-scope="scope" slot="header">
                  <div class="diyHeader">{{ scope.column.label }}</div>
                </template>
                <template slot-scope="scope">
                  <processSn :is-expedited="scope.row.isExpedited">
                    <span style="cursor:pointer;color:#406EFF" @click="toCheck(scope.row)">{{ scope.row.approvalNum ? handleSnNumber(scope.row.approvalNum) : '--' }}</span>
                  </processSn>
                </template>
              </u-table-column>
              <u-table-column :min-width="handleTdWidth(150,240)" align="left" label="结算名称">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.settleName" is-can-click @handelClick="toCheck(scope.row)" />
                </template>
              </u-table-column>
              <u-table-column :min-width="130" align="right" label="结算总金额(元)" sortable="custom" prop="settlementAmount">
                <template slot-scope="scope">
                  <PriceColumn :real-val="scope.row.settlementAmount" :price="scope.row.settlementAmount" />
                </template>
              </u-table-column>
              <u-table-column :min-width="handleTdWidth(110,130)" align="right" label="实付金额(元)">
                <template slot-scope="scope">
                  <PriceColumn :real-val="scope.row.actualAmount" :price="scope.row.actualAmount" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="付款状态">
                <template slot-scope="scope">
                  <span>{{ scope.row.examinePayStatus | examinePayStatus }}</span>
                </template>
              </u-table-column>
              <u-table-column align="left" label="申请人">
                <template slot-scope="scope">
                  <CheckUserInfo v-if="scope.row.proposer" :label="scope.row.proposer" :user-id="scope.row.proposerId" />
                  <div v-else>--</div>
                </template>
              </u-table-column>
              <u-table-column align="left" label="申请人部门" width="140">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.proposerDepartmentName" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="账户类型" width="120">
                <template slot-scope="scope">
                  {{ scope.row.accountType | accountTypeStatus }}
                </template>
              </u-table-column>
              <u-table-column align="left" label="供应商" width="120">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.supplier" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="成本来源" width="120">
                <template slot-scope="scope">
                  <ToolTip v-if="!scope.row.isNotOrder" :content="`${supplierCostBelong(scope.row.costBelong)}${scope.row.isInvite ? '(协作)' : ''}`" />
                  <div v-else>非订单</div>
                </template>
              </u-table-column>
              <u-table-column align="left" label="当前节点" width="120">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.currentNode" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="当前处理人" width="120">
                <template slot-scope="scope">
                  <ToolTip :content="scope.row.currentRole" />
                </template>
              </u-table-column>
              <u-table-column align="left" label="业务会计" width="120">
                <template slot-scope="scope">
                  <CheckUserInfo v-if="scope.row.businessAccounting" :label="scope.row.businessAccounting" :user-id="scope.row.businessAccountingId" />
                  <div v-else>--</div>
                </template>
              </u-table-column>
              <u-table-column :width="180" align="left" label="审批进度">
                <template slot-scope="scope">
                  <div style="display:flex;align-items:center">
                    <div :style="scope.row.listStatus === 4?{backgroundColor: '#31CC9C'}:{backgroundColor: '#FD8546'}" class="dot"/>
                    <span>{{ scope.row.listStatus | listProcessStatus }}</span>
                  </div>
                </template>
              </u-table-column>
              <u-table-column align="left" label="创建人">
                <template slot-scope="scope">
                  <CheckUserInfo v-if="scope.row.createUser" :label="scope.row.createUser" :user-id="scope.row.creatorId" />
                  <div v-else>--</div>
                </template>
              </u-table-column>
              <u-table-column align="left" label="创建时间" width="130">
                <template slot-scope="scope">
                  <span>{{ scope.row.createTime | format('YYYY/MM/DD HH:mm:ss') }}</span>
                </template>
              </u-table-column>
              <u-table-column align="left" label="计划支付日期" width="130" sortable="custom" prop="planPayTime">
                <template slot-scope="scope">
                  <span>{{ scope.row.planPayTime | format('YYYY/MM/DD') }}</span>
                </template>
              </u-table-column>
            </template>
            <u-table-column :width="operateWidth" fixed="right" align="left" label="操作">
              <template slot-scope="scope">
                <div class="flex-center">
                  <div v-if="!showMobilePage" class="button-text br" @click="toCheck(scope.row)">查看</div>
                  <MoreOpeator
                    :list="[
                      {
                        label: '查看',
                        handelClick: () => {toCheck(scope.row)},
                        auth: showMobilePage
                      },{
                        label: '删除',
                        handelClick: () => {toDel(scope.row)},
                        auth: !dimension,
                        disabled: !(scope.row.listStatus === 0 || scope.row.listStatus === -2 || scope.row.listStatus === 5)
                      },
                      // 审批单操作
                      {
                        label: '转交',
                        handelClick: () => {handleApproverChange(scope.row.id)},
                        auth: dimension && showApproverChangeBtn(scope.row.listStatus)
                      }, {
                        label: '付款',
                        handelClick: () => {toPay(scope.row.id)},
                        auth: dimension && scope.row.listStatus && scope.row.listStatus === 4 && !scope.row.examinePayStatus && hasRouteAuth('medium:supplierAudit:pay')
                      }, {
                        label: '撤回',
                        handelClick: () => {examineBack(scope.row.id)},
                        auth: dimension && scope.row.listStatus === 4 && hasRouteAuth('medium:supplierAudit:higherRecall')
                      },{
                        label: '申请余款',
                        handelClick: () => {againLaunch(scope.row)},
                        auth: dimension && !scope.row.isExamineing && (scope.row.listStatus === 3 || scope.row.listStatus === 4) && scope.row.listStatus !== 1 && isCreator(scope.row.creatorId)
                      },{
                        label: '修改',
                        handelClick: () => {toEdit(scope.row)},
                        auth: dimension && !scope.row.isExamineing && scope.row.listStatus && (scope.row.listStatus === 2 || scope.row.listStatus === 5) && scope.row.listStatus !== 1 && isCreator(scope.row.creatorId)
                      }
                    ]"
                  >
                    <div
                      v-if="!showMobilePage"
                      slot="button"
                      :class="{ 'disabled-more': dimension && (!scope.row.listStatus || !isExistBtn(scope.row)) }"
                      class="button-text">更多<i class="el-icon-arrow-down"/></div>
                    <el-image v-else slot="button" :src="operateBtns" class="table-dropdown-img"/>
                  </MoreOpeator>
                </div>
              </template>
            </u-table-column>
          </u-table>
          <empty-placeholder v-else-if="!isInit" style="margin-bottom: 24px" />
        </div>
        <el-row v-if="showMobilePage" type="flex" justify="left">
          <el-pagination
            v-show="list.total > 0"
            :current-page="list.page"
            :page-size="list.perPage"
            :total="list.total"
            :small="true"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="pageLayout"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
        <fixed-pagination>
          <template v-if="showMobilePage">
            <FilterInput
              ref="FilterToolRef"
              v-model="queryForm"
              :filter-list="filterList"
              show-search-btn
              show-mobile-icon
              @handelClick="queryClick"
              @queryEmpty="queryEmpty"
              @filterTagStatus="filterTagStatus">
              <div slot="checkGroup">
                <el-checkbox v-model="isShowMe" style="margin-right: 20px;" @change="queryClick" >我发起的</el-checkbox>
                <el-checkbox v-if="activeId !== -2" v-model="isMyApproval" @change="queryClick" >我审批的</el-checkbox>
                <el-checkbox v-model="isMyPending" @change="queryClick" >待我处理</el-checkbox>
              </div>
            </FilterInput>
            <MoreOpeator
              ref="moreOpeatorRef"
              :list="MoreOpeatorList"
              show-mobile-icon
            />
            <div class="mobile-bar">
              <el-dropdown
                v-if="hasRouteAuth('medium:supplierAudit:launch')"
                placement="bottom"
                trigger="click">
                <createBtn mobile-table/>
                <el-dropdown-menu slot="dropdown" style="padding:0;">
                  <el-dropdown-item style="width:130px;padding:0;text-align:center;" @click.native="toCreate(0)">
                    <div>订单成本付款结算</div>
                  </el-dropdown-item>
                  <el-dropdown-item style="width:130px;padding:0;text-align:center;" @click.native="toCreate(1)">
                    <div>其他付款结算(非订单)</div>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </template>
          <template v-else>
            <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
            <div class="flex"/>
            <div class="pagination-area">
              <el-pagination
                v-show="list.total > 0"
                :current-page="list.page"
                :page-size="list.perPage"
                :total="list.total"
                :page-sizes="[20, 50, 100, 250, 500]"
                layout="total, prev, pager, next, sizes, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
            </div>
          </template>
        </fixed-pagination>
      </div>
      <DiversAuditorDialog ref="auditorDialog" :can-empty="false" @handleSender="handleBatchSender" />
      <ApproverChange ref="approverChangeDialog" :business-type="BUSINESS_TYPE.SETTLE" :ids="curSelectedId" @changeCallBack="changeCallBack"/>
    </div>
  </div>
</template>
<script>
import DiversAuditorDialog from '@/components/Common/auditProcess/module/diversAuditorDialog';
import ApproverChange from '@/components/Common/auditProcess/approverChange';
import dataDisplay from '@/components/Common/baseComponent/dataDisplay';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import createBtn from '@/components/Common/baseComponent/createBtn';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import ClearBtn from '@/components/Common/ClearBtn';
import ListTab from '@/components/ListTab';
import Title from '@/components/Title';
import { getSupplierTab, getSupplierList, supplierListDel, getSupplierApprovalTab,
  getSupplierApprovalList, examinePay, examineCancel, getSupplierStatistics } from '@/api/supplier';
import { getDepartmentAll, costList } from '@/api/config';
import { deptList } from '@/api/select';
import { supplierStatus, accountTypeStatus, supplierCostBelong, examinePayStatus, listProcessStatus, expeditedOptions } from '@/filters/status';
import { format } from '@/filters/date';
import { paramsAryToStr, paramsRangeFormat } from '@/utils/paramsFormat';
import { PROCESS_TYPE, BUSINESS_TYPE } from '@/utils/const/process';
import { CURRENT_NODE_MODULE } from '@/utils/const';
import { hasRouteAuth } from '@/utils/permission';
import { encryption } from '@/utils';
import options from '@/views/legal/module/options';
import { showModal } from '@/utils/message';
import { handelProgess } from '@/utils/process';
import { mapState } from 'vuex';
import axios from 'axios';
import filterObjStoreMixin from '@/mixins/filterObjStore';
import approverChange from '@/mixins/approverChange';
import tableSelections from '@/mixins/tableSelections';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';
import copyLink from '@/mixins/copyLink';
import schedule from '@/mixins/schedule';
import incomeAmountIcon from '@/assets/chargeOffDetail/incomeAmount.png';
import costIcon from '@/assets/dataDisplay/icon_45.png';
import icon_7 from '@/assets/dataDisplay/icon_7.png';
import rmb from '@/assets/dataDisplay/rmb.png';
import setting from '@/assets/setting.png';

export default {
  name: 'SupplierAccount',
  components: { ClearBtn, Title, EmptyPlaceholder, format, createBtn, MoreOpeator, ListTab,
    ApproverChange, dataDisplay, DiversAuditorDialog },
  filters: {
    supplierStatus, accountTypeStatus,
    format, examinePayStatus, listProcessStatus
  },
  provide() {
    return {
      getActiveTabs: () => this.dimension ? 'approval' : 'settle'
    };
  },
  mixins: [TableAdaptive, tableSelections, mobileTable, filterObjStoreMixin, copyLink, schedule, approverChange],
  data() {
    return {
      incomeAmountIcon,
      costIcon,
      rmb,
      icon_7,
      setting,
      activeId: -1,
      tabList: [],
      isInit: true,
      isShowMe: false,
      isMyApproval: false,
      isMyPending: false,
      queryForm: {},
      page: 1,
      perPage: 20,
      BUSINESS_TYPE,
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInint: true
      },
      listLoading: true,
      cancelToken: null,
      sortType: '',
      sortName: '',
      deptOption: [], // 部门列表
      deptTreeList: [],
      isUmyTable: true,
      dimension: 0, // 列表展示维度：0结算单，1审批单
      tableRefName: 'tableRef', // 表格的ref名称
      idKey: 'id', // 唯一表示字段
      invoiceOptions: [ // 发票状态下拉选项
        { value: 0, label: '已取得' },
        { value: 1, label: '未取得' },
        { value: 2, label: '无需发票' },
        { value: 3, label: '财务统一申请' },
        { value: 4, label: '业务统一申请' }
      ],
      costItem: null,
      statisticsData: {},
      rangeKeyArr: [{
        attr: 'planPayTime',
        start: 'planPayStartTime',
        end: 'planPayEndTime',
        type: 'time',
        addTime: true
      }, {
        attr: 'actualPayTime',
        start: 'actualPayStartTime',
        end: 'actualPayEndTime',
        type: 'time',
        addTime: true

      }, {
        attr: 'createTime',
        start: 'createTimeStart',
        end: 'createTimeEnd',
        type: 'time',
        addTime: true
      }]
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    arrayKeyArr() {
      return ['currentNode', 'costItemNames'];
    },
    modeList() {
      return [
        { mode: 0, name: '结算单', handleClick: this.toggleDimension },
        { mode: 1, name: '审批单', handleClick: this.toggleDimension }
      ];
    },
    filterList() {
      const settleArr = [
        { keyword: 'supplierNum', name: '结算单号', labelWidth: '96px', type: 'input' },
        { keyword: 'settleName', name: '结算名称', labelWidth: '96px', type: 'input' },
        { keyword: 'orderNum', name: '订单编号', labelWidth: '96px', type: 'input' },
        { keyword: 'supplier', name: '供应商名称', labelWidth: '96px', type: 'input' },
        { keyword: 'company', name: '所属公司', labelWidth: '96px', type: 'input' },
        { keyword: 'settleCreateUser', name: '结算单创建人', labelWidth: '96px', type: 'input' },
        { keyword: 'createUser', name: '审批单创建人', labelWidth: '96px', type: 'input' },
        { keyword: 'proposer', name: '审批单申请人', labelWidth: '96px', type: 'input' },
        { keyword: 'approvalUser', name: '审批单审批人', labelWidth: '96px', type: 'input' },
        { keyword: 'currentRole', name: '当前处理人', labelWidth: '96px', type: 'input' },
        { keyword: 'reviewNum', name: '审批单号', labelWidth: '96px', type: 'input' },
        { keyword: 'costNum', name: '成本编号', labelWidth: '96px', type: 'input' },
        { keyword: 'comment', name: '评论', type: 'input', labelWidth: '96px' },
        { keyword: 'approvalComment', name: '审批意见', type: 'input', labelWidth: '96px' },
        { keyword: 'settleAmount', labelWidth: '96px', name: '结算总金额', type: 'inputRange' },
        { keyword: 'proposerDepartment', name: '申请人部门', type: 'cascaderSelectWithChild', childrenVal: 'children', options: this.deptTreeList },
        { keyword: 'paymentBelong', name: '款项归属', type: 'cascaderSelectWithChild', childrenVal: 'children', options: this.deptTreeList },
        { keyword: 'costBelong', name: '成本来源', type: 'select', options: [
          // { value: -1, label: '全部' }
          { value: 0, label: '渠道订单' },
          { value: 1, label: '项目订单' },
          { value: 2, label: '商务订单' },
          { value: 3, label: '营销授权' },
          { value: 5, label: '项目渠道单' },
          { value: 9, label: '非订单' }
        ] },
        { keyword: 'accountType', name: '账户类型', type: 'select', options: [
          { value: 1, label: '第三方账户' },
          { value: 2, label: '对公银行账户' },
          { value: 3, label: '对公其他账户' }
        ] },
        { keyword: 'invioce', name: '发票', type: 'select', options: this.invoiceOptions },
        { keyword: 'invioceStatus', name: '发票状态', type: 'select', options: [
          { value: 0, label: '已填写' },
          { value: 1, label: '未填写' }
        ] },
        { keyword: 'costItemNames', name: '成本项', type: 'mulSelect', isSearch: true, options: this.costItem },
        {
          keyword: 'currentNode',
          name: '当前节点',
          type: 'loadMoreSelect',
          valueName: 'name',
          directShow: true,
          multiple: true,
          extendParams: { type: CURRENT_NODE_MODULE.SUPPLIER },
          labelName: 'name',
          placeholder: '当前节点',
          apiUrl: 'admin/common/currentNodes',
          searchkeyword: 'keyword'
        },
        { keyword: 'isExpedited', name: '是否加急', type: 'select', options: expeditedOptions },
        { keyword: 'examinePayStatus', name: '付款状态', type: 'select', options: [{ value: 0, label: '未付款' }, { value: 1, label: '已付款' }] },
        { keyword: 'createMethod', name: '发起方式', type: 'select', options: [
          { value: 0, label: '手动新建' }, { value: 1, label: '智能结算' }
        ] },

        { keyword: 'planPayTime', labelWidth: '96px', name: '计划支付日期', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'actualPayTime', labelWidth: '96px', name: '实际支付日期', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'createTime', labelWidth: '96px', name: '创建时间', timeType: 'daterange', type: 'rangeDate' }
      ];
      const approvalArr = [
        { keyword: 'approvalNum', name: '审批单号', labelWidth: '96px', type: 'input' },
        { keyword: 'settleName', name: '结算名称', labelWidth: '96px', type: 'input' },
        { keyword: 'settleAmount', name: '结算总金额', labelWidth: '96px', type: 'inputRange' },
        { keyword: 'actualAmount', name: '实付金额', labelWidth: '96px', type: 'inputRange' },
        { keyword: 'proposer', name: '申请人', labelWidth: '96px', type: 'input' },
        { keyword: 'supplier', name: '供应商', labelWidth: '96px', type: 'input' },
        { keyword: 'currentRole', name: '当前处理人', labelWidth: '96px', type: 'input' },
        { keyword: 'businessAccounting', name: '业务会计', labelWidth: '96px', type: 'input' },
        { keyword: 'createUser', name: '创建人', labelWidth: '96px', type: 'input' },
        { keyword: 'comment', name: '评论', type: 'input', labelWidth: '96px' },
        { keyword: 'approvalComment', name: '审批意见', type: 'input', labelWidth: '96px' },
        { keyword: 'examinePayStatus', name: '付款状态', isSearch: true, type: 'select', options: [{ value: 0, label: '未付款' }, { value: 1, label: '已付款' }] },
        { keyword: 'proposerDepartment', name: '申请人部门', type: 'cascaderSelectWithChild', childrenVal: 'children', options: this.deptTreeList },
        { keyword: 'accountType', name: '账户类型', type: 'select', options: [
          { value: 1, label: '第三方账户' },
          { value: 2, label: '对公银行账户' },
          { value: 3, label: '对公其他账户' }
        ] },
        { keyword: 'costBelong', name: '成本来源', type: 'select', options: [
          { value: 0, label: '渠道订单' },
          { value: 1, label: '项目订单' },
          { value: 2, label: '商务订单' },
          { value: 3, label: '营销授权' },
          { value: 5, label: '项目渠道单' },
          { value: 9, label: '非订单' }
        ] },
        {
          keyword: 'currentNode',
          name: '当前节点',
          type: 'loadMoreSelect',
          valueName: 'name',
          directShow: true,
          multiple: true,
          extendParams: { type: CURRENT_NODE_MODULE.SUPPLIER },
          labelName: 'name',
          placeholder: '当前节点',
          apiUrl: 'admin/common/currentNodes',
          searchkeyword: 'keyword'
        },
        { keyword: 'listStatus', name: '审批进度', isSearch: true, type: 'select', options: [...options.auditOptions] },
        { keyword: 'createTime', labelWidth: '96px', name: '创建时间', timeType: 'daterange', type: 'rangeDate' },
        { keyword: 'planPayTime', labelWidth: '96px', name: '计划支付日期', timeType: 'daterange', type: 'rangeDate' }
      ];
      return this.dimension ? approvalArr : settleArr;
    },
    MoreOpeatorList() {
      const settleList = [
        { label: '批量导出', exportApi: `admin/supplier/batchExport`, auth: this.hasRouteAuth('medium:supplierAudit:batchExport'), type: 'export', exportName: '付款申请', isBeforeExport: true, beforeExport: this.exportBeforeExport, refName: 'supplierExportRef' },
        { label: '导出审批单', exportApi: `admin/supplier/examineExport`, auth: this.hasRouteAuth('medium:supplierAudit:batchExport'), type: 'export', exportName: '付款申请审批单', isBeforeExport: true, beforeExport: this.examineBeforeExport, refName: 'examineExportRef' },
        { label: '批量抄送', handelClick: this.handleSendMsg },
        { label: '复制链接', handelClick: this.batchCopyLink }
      ];
      const approvalList = [
        { label: '导出审批单', exportApi: `admin/supplier/approval/export`, auth: this.hasRouteAuth('medium:supplierAudit:batchExport'), type: 'export', exportName: '付款申请审批单', isBeforeExport: true, beforeExport: this.examineBeforeExport, refName: 'examineExportRef' },
        { label: '导出收款人', exportApi: 'admin/supplier/payeeExport', auth: this.hasRouteAuth('medium:supplierAudit:batchExport'), type: 'export', exportName: '付款申请收款人', isBeforeExport: true, beforeExport: this.payeeBeforeExport, refName: 'payeeExportRef' },
        { label: '批量抄送', handelClick: this.handleSendMsg },
        { label: '复制链接', handelClick: this.batchCopyLink },
        { label: '批量转交', handelClick: () => this.handleBatchApproverChange(BUSINESS_TYPE.SETTLE) }
      ];
      return this.dimension ? approvalList : settleList;
    },
    tableOutsideHeight() {
      return this.showMobilePage ? 256 : 246;
    }
  },
  watch: {
    list: {
      handler(val) {
        this.$nextTick(() => {
          if (this.setSelectRow) this.setSelectRow(val.items);
        });
      },
      deep: true
    }
  },
  beforeRouteEnter(to, from, next) {
    if (from.name === 'supplierDetail') {
      to.meta.isChange = true;
    } else {
      to.meta.isChange = false;
    }
    next();
  },
  created() {
    this.initDimension();
    this.getDeptList();
    this.queryDeptTreeList();
    this.getCostItemList();
  },
  activated() {
    if (this.$route.meta.isChange) {
      this.fetchData(false);
    } else {
      const hasDefaultPresetFilter = this.$refs.FilterToolRef && this.$refs.FilterToolRef.hasDefaultPresetFilter;
      if (!hasDefaultPresetFilter) {
        if (this.$route.query.status !== undefined) {
          this.activeId = Number(this.$route.query.status);
        } else {
          this.activeId = -1;
        }
        if (this.$route.query.taskTimeStart) { // 筛选账号批量结算的结算单
          this.queryForm = {};
          const { taskTimeStart, taskTimeEnd, userName } = this.$route.query;
          this.$set(this.queryForm, 'createTime', [taskTimeStart, taskTimeEnd]);
          this.$set(this.queryForm, 'settleCreateUser', userName);
        }
        this.fetchData(true);
      }
    }
  },
  methods: {
    handelProgess,
    hasRouteAuth,
    supplierCostBelong,
    getListStatus(status) {
      if (status === undefined || status === null) return '--';
      const statusMap = {
        0: '待提交',
        6: '审批中',
        1: '部分结算',
        2: '未过审',
        3: '已作废',
        4: '已完成',
        5: '已关闭'
      };
      statusMap[-2] = '草稿中';
      return statusMap[status];
    },
    getDetailLink(item) {
      const settleId = this.dimension ? item.examineId : item.id;
      const id = item.supplierId;
      const inviteCode = encryption(settleId);
      let link = `${location.origin}#/businessPage/supplierDetail?settleId=${settleId}&id=${id}&isSettle=true`;
      if (item.isNotOrder) link = link + '&isNotOrder=1';
      if (item.isInvite) link = link + `&isInvite=${inviteCode}`;
      return link;
    },
    isCreator(id) {
      return id === this.userInfo.id;
    },
    showApproverChangeBtn(status) {
      return status && status !== -1 && status !== 4;
    },
    // 判断审批单维度更多下是否有按钮
    isExistBtn(row) {
      const isExistApproveBtn = this.showApproverChangeBtn(row.listStatus); // 审批转交
      const isExistPayBtn = row.listStatus && row.listStatus === 4 && !row.examinePayStatus && this.hasRouteAuth('medium:supplierAudit:pay'); // 付款
      const isExistRecallBtn = row.listStatus && row.listStatus === 4 && this.hasRouteAuth('medium:supplierAudit:higherRecall'); // 撤回
      const isExistLaunchBtn = !row.isExamineing && (row.listStatus === 3 || row.listStatus === 4) && row.listStatus !== 1 && this.isCreator(row.creatorId); // 申请余款
      const isExistEditBtn = !row.isExamineing && row.listStatus && (row.listStatus === 2 || row.listStatus === 5) && row.listStatus !== 1 && this.isCreator(row.creatorId); // 修改
      return isExistApproveBtn || isExistPayBtn || isExistRecallBtn || isExistLaunchBtn || isExistEditBtn;
    },
    handleApproverChange(id) {
      this.curSelectedId = id + '';
      this.$refs['approverChangeDialog'].dialogVisible = true;
    },
    toPay(id) {
      showModal('请确认是否已支付？', '', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        lockScroll: false,
        center: true,
        customClass: 'del-message del-message-cancel',
        iconClass: 'del-icon'
      }).then(() => {
        examinePay(id).then(res => {
          this.$message.success('付款成功');
          this.fetchData(true);
        }).catch(err => {
          console.error(err);
        });
      });
    },
    examineBack(id) {
      showModal('当前审批任务已完成，撤回后审批任务重新开始，请谨慎操作', '', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        lockScroll: false,
        center: true,
        iconClass: 'del-icon'
      }).then(() => {
        examineCancel({ id }).then(res => {
          if (res.code === 200) {
            this.$message.success('撤回成功');
            this.fetchData(true);
          } else {
            this.$message.error(res.message);
          }
        });
      });
    },
    againLaunch(item) {
      const query = {
        settleId: this.dimension ? item.examineId : item.id,
        id: item.supplierId,
        isSettle: true,
        isAgainLaunch: true
      };
      if (item.isNotOrder) query.isNotOrder = 1;
      this.$router.push({
        name: 'supplierDetail',
        query,
        params: item
      });
    },
    toEdit(item) {
      // 审批单才有编辑
      if (!this.dimension) return;
      const settleId = item.examineId; // 结算id
      const examineId = item.id; // 审批单id
      const query = {
        settleId,
        examineId,
        id: item.supplierId
      };
      if (item.isNotOrder) query.isNotOrder = 1;
      this.$router.push({
        name: 'supplierEdit',
        query
      });
    },
    toCheck(item) {
      const query = {
        settleId: this.dimension ? item.examineId : item.id,
        id: item.supplierId,
        isSettle: true,
        fromList: 1
      };
      if (item.isNotOrder) query.isNotOrder = 1;
      if (item.isInvite) {
        query.isInvite = encryption(this.dimension ? item.examineId : item.id);
      }
      if (this.dimension) query.dimension = this.dimension;
      const params = this.dimension ? item : { ...this.$route.params };
      this.filterObjStore(PROCESS_TYPE.SETTLE);
      this.$router.push({
        name: 'supplierDetail',
        query,
        params
      });
    },
    toDel(item) {
      this.$confirm('是否确定删除该结算单', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        center: true,
        type: 'warning',
        customClass: ' del-message del-message-cancel',
        iconClass: 'del-icon'
      }).then(() => {
        supplierListDel(item.id).then(res => {
          this.$message.success('删除成功');
          if (this.page > 1 && this.perPage * (this.page - 1) + 1 === this.list.total) {
            this.page--;
          }
          this.resetItemSelected(item.id);
          this.fetchData(true);
        }).catch(err => {
          console.error(err);
        });
      }).catch(() => {
        return;
      });
    },
    // 排序
    sortMethod(a) {
      if (a.order) {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      } else {
        this.sortName = '';
        this.sortType = '';
      }
      this.queryClick();
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.queryForm = {};
      this.sortName = '';
      this.sortType = '';
      this.isShowMe = false;
      this.isMyApproval = false;
      this.isMyPending = false;
      this.fetchData(true);
    },
    handleTabClick(id) {
      this.activeId = id;
      if (this.activeId === -2) {
        this.isMyApproval = false;
      }
      this.queryClick();
    },
    formatParams() {
      const queryForm = JSON.parse(JSON.stringify(this.queryForm));
      const params = { ...queryForm, page: this.page, perPage: this.perPage };
      params.status = this.activeId;
      params.isShowMe = this.isShowMe;
      params.isMyApproval = this.isMyApproval;
      params.isMyPending = this.isMyPending;
      params.sortType = this.sortType;
      params.sortName = this.sortName;
      paramsRangeFormat(this.rangeKeyArr, params);
      paramsAryToStr(this.arrayKeyArr, params);
      if (params.settleAmount && Array.isArray(params.settleAmount) && params.settleAmount.length === 2) {
        params.settleAmountBegin = params.settleAmount[0];
        params.settleAmountEnd = params.settleAmount[1];
      }
      if (params.actualAmount && Array.isArray(params.actualAmount) && params.actualAmount.length === 2) {
        params.actualAmountBegin = params.actualAmount[0];
        params.actualAmountEnd = params.actualAmount[1];
      }
      delete params.actualAmount;
      delete params.settleAmount;
      if (params.paymentBelong && Array.isArray(params.paymentBelong))params.paymentBelong = params.paymentBelong.join(',');
      if (params.proposerDepartment && Array.isArray(params.proposerDepartment))params.proposerDepartment = params.proposerDepartment.join(',');
      return params;
    },
    getSupplierStatistics() {
      const params = this.formatParams();
      getSupplierStatistics(params).then(res => {
        if (res.code === 200) {
          this.statisticsData = res.data;
        }
      }).catch(err => {
        console.log(err);
      });
    },
    async fetchData(reset = false) {
      if (reset) this.page = 1;
      const params = this.formatParams();
      this.getSupplierStatistics();
      if (this.cancelToken) this.cancelToken.cancel('cancel');
      const source = axios.CancelToken.source();
      this.cancelToken = source;
      this.listLoading = true;
      this.getTabList();
      try {
        const res = this.dimension ? await getSupplierApprovalList(params, source.token) : await getSupplierList(params, source.token);
        this.isInit = false;
        if (res.code === 200) {
          this.list = res.data;
        }
        this.list.isInint = false;
        this.listLoading = false;
      } catch (error) {
        this.listLoading = false;
        console.error(error);
      }
    },
    async getTabList() {
      try {
        const params = this.formatParams();
        const result = this.dimension ? await getSupplierApprovalTab(params) : await getSupplierTab(params);
        if (result.code === 200) {
          this.tabList = result.data;
        }
      } catch (error) {
        console.log(error);
      }
    },
    exportBeforeExport() {
      const params = this.formatParams();
      if (this.multipleSelectionAll.length) {
        params.ids = this.multipleSelectionAll.map(el => el.id).join(',');
      }
      if (this.$refs.moreOpeatorRef) {
        this.$refs.moreOpeatorRef.btnExport(params, 'supplierExportRef');
      }
    },
    // 导出收款人
    payeeBeforeExport() {
      const params = this.formatParams();
      if (this.multipleSelectionAll.length) {
        params.ids = this.multipleSelectionAll.map(el => el.id).join(',');
      }
      if (this.$refs.moreOpeatorRef) {
        this.$refs.moreOpeatorRef.btnExport(params, 'payeeExportRef');
      }
    },
    // 审批单导出
    examineBeforeExport() {
      const params = this.formatParams();
      if (this.multipleSelectionAll.length) {
        params.ids = this.multipleSelectionAll.map(el => el.id).join(',');
      }
      if (this.$refs.moreOpeatorRef) {
        this.$refs.moreOpeatorRef.btnExport(params, 'examineExportRef');
      }
    },
    async getDeptList() {
      const res = await deptList();
      res.data.forEach(i => {
        i.label = i.value;
        i.value = i.id;
      });
      this.deptOption = res.data;
    },
    initDimension() { // 默认以结算单维度展示，有缓存则取缓存值
      const localDimension = localStorage.getItem('supplierDimension');
      this.dimension = Number(localDimension) || Number(localDimension) === 0 ? Number(localDimension) : 0;
    },
    toggleDimension(type) {
      this.dimension = type;
      localStorage.setItem('supplierDimension', this.dimension);
      this.queryForm = {};
      this.activeId = this.tabList[0].id;
      this.fetchData(true);
      this.multipleSelectionAll = [];
      this.$nextTick(() => {
        this.$refs.FilterToolRef.changeSelectKey();
      });
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData(true);
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    handleCurrentChange(toPage) {
      this.page = toPage;
      this.fetchData();
      this.$nextTick(() => {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
      });
    },
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    filterStatus(status) {
      switch (status) {
        case 0:
        case 4:
          return {
            backgroundColor: '#FFEFE6',
            color: '#FD8546'
          };
        case 1:
          return {
            backgroundColor: '#eff3fb',
            color: '#406eff'
          };
        case 2:
          return {
            backgroundColor: '#dff8f0',
            color: '#31CC9C'
          };
        case 3:
          return {
            backgroundColor: '#F7ECEC',
            color: '#E02020'
          };
        default:
          break;
      }
    },
    toCreate(type) {
      const params = { name: 'supplierCreate' };
      if (type === 1) params.query = { isNotOrder: 1 };
      this.$router.push(params);
    },
    getCostItemList() {
      costList({ getAll: 1 }).then(res => {
        if (res.data) {
          const costItem = res.data.items;
          const costItemList = [];
          costItem.forEach(item => {
            if (!costItemList.find(cost => cost.label === item.costName)) {
              const obj = {
                // value: item.costId,
                value: item.costName,
                label: item.costName
              };
              costItemList.push(obj);
            }
          });
          this.costItem = costItemList;
        }
      });
    },
    goBatchSettle() {
      this.$router.push({
        name: 'batchSettle'
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.supplier-account {
  .table-list {
    margin: 16px 16px 0 16px;
    background-color: #fff;
    padding: 20px 20px 55px 20px;
    overflow: hidden;
  }
  .tab-box {
    margin-bottom: 16px;
    .mode-switch-container {
      box-shadow: none;
      margin-right: 0;
    }
    .flex-1 {
      flex: 1;
      width: 0;
    }
  }
  .dot {
    width: 4px;
    height: 4px;
    border-radius: 50%;
    margin-right: 5px;
  }
  .pagination-area {
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
  .flex {
    flex:1;
  }
}
.opeator-bar {
  display: flex;
}
.mobile-bar {
  flex: 1;
  &::v-deep {
    .el-dropdown, .el-button{
      width: 100%;
    }
  }
}
.disabled-more {
  cursor: not-allowed;
  color: #bbb;
}
.supplier-tool {
  display: flex;
  position:relative;
  margin-bottom:16px;
}
.progress-cell {
  ::v-deep .el-progress__text {
    font-size: 14px !important;
    color: #333;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    max-width: 56px;
  }
}
</style>
